package com.jintu.portal.service.datadriver.receiver;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.cache.RedisHelper;
import com.jintu.portal.service.datadriver.DataRequestHandler;
import com.jintu.portal.service.datadriver.pojo.MsgRespCode;
import com.jintu.portal.service.datadriver.pojo.RespInfo;
import com.jintu.portal.service.datadriver.pojo.Response;
import com.jintu.portal.service.datadriver.pojo.SysRespCode;
import com.jintu.portal.service.datadriver.pojo.entity.SourceData;
import com.jintu.portal.service.datadriver.repository.SourceDataMongoDao;
import com.jintu.portal.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * @author very
 */
@Slf4j
@RestController
@RequestMapping("/receive/xueXinReceiver")
public class XueXinReceiver {

    private static final String QUERY_EDUCATION = "QUERY_EDUCATION";
    private static final String QUERY_STUDENT = "QUERY_STUDENT";

    @Resource(name = "sourceDataMongoDao")
    private SourceDataMongoDao sourceDataMongoDao;

    @Resource(name = "redisHelper")
    private RedisHelper redisHelper;

    @Resource(name = "dataRequestHandler")
    private DataRequestHandler dataRequestHandler;

    @Resource(name = "receiverCommonUtil")
    private ReceiverCommonUtil receiverCommonUtil;

    @RequestMapping(method = RequestMethod.POST)
    public JSONObject receive(@RequestBody Response response) {
        JSONObject ret = new JSONObject();
        ret.put("code", "0000");
        try {
            log.info("学信网数据爬取成功，原始返回数据为：{}", JSONObject.toJSONString(response));
            String merchPrivateString = response.getMerchPrivate();
            if (StringUtils.isBlank(merchPrivateString)) {
                log.error("用户merchPrivate为空，无法还原风控订单信息");
            } else {
                JSONObject riskOrderInfo = JSONObject.parseObject(merchPrivateString);
                if (SysRespCode.QUERY_SUCCESS.getCode().equals(response.getRetCode())) {
                    RespInfo respInfo = response.getRetInfo();
                    String orderId = riskOrderInfo.getString("orderId");
                    if (respInfo != null && MsgRespCode.SEARCH.getCode().equals(respInfo.getCode())) {
                        String tradeNo = redisHelper.get(riskOrderInfo.getString("dataSourceCode") + "_" + orderId);
                        if (StringUtils.isBlank(tradeNo)) {
                            log.error("风控订单【{}】从数据库中获取tradeNo为空，学信网数据爬去失败", orderId);
                        } else {
                            log.info("开始获取学信网原始数据信息");
                            queryXueXinData(riskOrderInfo, tradeNo);
                        }
                    }
                }
                receiverCommonUtil.changeFlagAndSendMq(riskOrderInfo, null);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ret;
    }

    private void queryXueXinData(JSONObject riskOrderInfo, String tradeNo) throws Exception {
        String collectionName = riskOrderInfo.getString("dataSourceCode");
        SourceData xueXinData = new SourceData();
        xueXinData.setId(CommonUtil.genMongoId(riskOrderInfo.getString("orderId"), riskOrderInfo.getInteger("userId")));
        xueXinData.setOrderId(riskOrderInfo.getString("orderId"));
        xueXinData.setUserId(riskOrderInfo.getInteger("userId"));
        xueXinData.setTimestamp(System.currentTimeMillis());
        JSONObject req = new JSONObject();
        req.put("tradeNo", tradeNo);
        req.put("optType", QUERY_EDUCATION);
        Document dataDoc = new Document();
        // 获取原始数据解析并存储
        // QUERY_EDUCATION
        String responseContent = dataRequestHandler.sendDataRequest(
                receiverCommonUtil.genDataRequestOrderId(riskOrderInfo.getString("orderId")),
                riskOrderInfo.getString("orderId"),
                riskOrderInfo.getString("dataSourceInterface"),
                req.toJSONString());
        Response response = JSONObject.parseObject(responseContent, Response.class);
        if (SysRespCode.QUERY_SUCCESS.getCode().equals(response.getRetCode()) && MsgRespCode.SEARCH.getCode().equals(response.getRetInfo().getCode())) {
            String dataStr = (String) response.getRetInfo().getMessage();
            JSONObject data = JSONObject.parseObject(dataStr);
            dataDoc.put(QUERY_EDUCATION, data);
            log.info("【{}】学信网 <QUERY_EDUCATION> 数据获取 collection - 【{}】, _id - 【{}】 - 成功"
                    , riskOrderInfo.getString("orderId"), collectionName, xueXinData.getId());
        } else {
            log.info("【{}】学信网 <QUERY_EDUCATION> 数据获取 - 失败", riskOrderInfo.getString("orderId"));
        }
        //QUERY_STUDENT
        req.put("optType", QUERY_STUDENT);
        String responseContent2 = dataRequestHandler.sendDataRequest(
                receiverCommonUtil.genDataRequestOrderId(riskOrderInfo.getString("orderId")),
                riskOrderInfo.getString("orderId"),
                riskOrderInfo.getString("dataSourceInterface"),
                req.toJSONString());
        Response response2 = JSONObject.parseObject(responseContent2, Response.class);
        if (SysRespCode.QUERY_SUCCESS.getCode().equals(response.getRetCode()) && MsgRespCode.SEARCH.getCode().equals(response.getRetInfo().getCode())) {
            String dataStr = (String) response2.getRetInfo().getMessage();
            JSONObject data = JSONObject.parseObject(dataStr);
            dataDoc.put(QUERY_STUDENT, data);
            log.info("【{}】学信网 <QUERY_STUDENT> 数据获取 collection - 【{}】, _id - 【{}】 - 成功"
                    , riskOrderInfo.getString("orderId"), collectionName, xueXinData.getId());
        } else {
            log.info("【{}】学信网 <QUERY_STUDENT> 数据获取 - 失败", riskOrderInfo.getString("orderId"));
        }
        xueXinData.setData(dataDoc);
        sourceDataMongoDao.saveSourceData(xueXinData, collectionName);
    }
}
